package com.wyc.jt808.server;

import com.wyc.jt808.codec.MsgDecoder;
import com.wyc.jt808.common.TPMSConsts;
import com.wyc.jt808.dao.DqJt808LocationInfoMapper;
import com.wyc.jt808.dao.DqVehicleInfoMapper;
import com.wyc.jt808.handler.TCPServerHandler;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class JT808ChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Value("${netty.read-timeout}")
    private int readTimeOut;

    @Autowired
    @Qualifier("businessGroup")//开了50个线程来确保并发性
    private EventExecutorGroup businessGroup;
    @Autowired
    private TCPServerHandler tcpServerHandler;//单例注入

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(new IdleStateHandler(readTimeOut, 0, 0, TimeUnit.MINUTES));
        // jt808协议 包头最大长度16+ 包体最大长度1023+分隔符2+转义字符最大姑且算60 = 1100
        pipeline.addLast(
                new DelimiterBasedFrameDecoder(1100, Unpooled.copiedBuffer(new byte[]{TPMSConsts.pkg_delimiter}),
                        Unpooled.copiedBuffer(new byte[]{TPMSConsts.pkg_delimiter, TPMSConsts.pkg_delimiter})));
        pipeline.addLast(businessGroup, tcpServerHandler);//涉及到数据库操作，所以放入businessGroup
    }
}
